package com.bootx.redis.listener;

import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
import io.lettuce.core.cluster.pubsub.api.async.NodeSelectionPubSubAsyncCommands;
import io.lettuce.core.cluster.pubsub.api.async.PubSubAsyncNodeSelection;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 检测redis的所有db
 * @author Tony.niu (hystrix0779@yeah.net)
 * @version V1.0
 * @date 2020/8/19
 **/
@Component
@Slf4j
public class RedisKeyExpirationListener extends RedisPubSubAdapter {

    private static final String EXPIRED_CHANNEL = "__keyevent@0__:expired";


    @Resource
    RedisClusterClient clusterClient;

    @Autowired
    private ListenerGrooveAdapter clusterGrooveAdapter;


    /**
     * 启动监听 注意:一定要在springboot启动类里边实现CommandLineRunner接口
     * 然后在run方法里边启动监听，不然不会生效，也不会报错
     */
    public void startListener() {
        // 异步订阅
        StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(clusterGrooveAdapter);

        PubSubAsyncNodeSelection<String, String> masters = pubSubConnection.async().masters();
        NodeSelectionPubSubAsyncCommands<String, String> commands = masters.commands();
        commands.subscribe(EXPIRED_CHANNEL);
    }
}

